package com.example.memorypoint.API;

import android.util.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.memorypoint.BuildConfig;

import okhttp3.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class GeminiClient {

    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .callTimeout(60, TimeUnit.SECONDS)
            .build();

    private static final String API_KEY = BuildConfig.GEMINI_API_KEY;  // 从 BuildConfig 中读取 Gemini API 密钥
    private static final String API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=" + API_KEY;

    public static String getResponseWithOkHttpAndFastJson(String prompt, String message) throws IOException {
        // 参数验证
        if (prompt == null || prompt.isEmpty()) {
            throw new IllegalArgumentException("Prompt must not be blank.");
        }
        if (message == null || message.isEmpty()) {
            throw new IllegalArgumentException("Message must not be blank.");
        }

        // 存储对话消息
        List<Map<String, Object>> contents = new ArrayList<>();

        // 添加系统消息
        Map<String, Object> systemMessage = new HashMap<>();
        systemMessage.put("role", "assistant");
        List<Map<String, String>> systemParts = new ArrayList<>();
        Map<String, String> systemPart = new HashMap<>();
        systemPart.put("text", prompt);  // 系统提示
        systemParts.add(systemPart);
        systemMessage.put("parts", systemParts);
        contents.add(systemMessage);

        // 添加用户消息
        Map<String, Object> userMessageMap = new HashMap<>();
        userMessageMap.put("role", "user");
        List<Map<String, String>> userParts = new ArrayList<>();
        Map<String, String> userPart = new HashMap<>();
        userPart.put("text", message);  // 用户消息
        userParts.add(userPart);
        userMessageMap.put("parts", userParts);
        contents.add(userMessageMap);

        Log.d("GeminiClient", "User message: " + message);
        Log.d("GeminiClient", "System message: " + prompt);

        // 构建请求体
        Map<String, Object> reqBody = new HashMap<>();
        reqBody.put("contents", contents);
        reqBody.put("model", "gemini-1.5-flash");

        // 将请求体转换为 JSON 字符串
        String requestBody = JSON.toJSONString(reqBody);
        MediaType mediaType = MediaType.parse("application/json");
        Log.e("GeminiClient", "Request body: " + requestBody);

        Request request = new Request.Builder()
                .url(API_URL)
                .addHeader("Content-Type", "application/json")
                .post(RequestBody.create(requestBody, mediaType))
                .build();

        try {
            // 发起请求
            Response response = client.newCall(request).execute();

            // 检查响应码是否为 200 OK
            if (response.code() != 200) {
                Log.e("GeminiClient", "Unexpected response code: " + response.code());

                // 打印 API 返回的错误信息
                String errorResponse = response.body().string();
                Log.e("GeminiClient", "Error response: " + errorResponse);
                throw new IOException("Unexpected response code: " + response.code());
            }

            // 获取响应体内容
            String responseBody = response.body().string();
            Log.d("GeminiClient", "Response body: " + responseBody);

            // 解析 JSON 响应体
            JSONObject responseObject = JSON.parseObject(responseBody);

            // 获取 candidates 数组，而不是 contents
            JSONArray candidatesArray = responseObject.getJSONArray("candidates");

            if (candidatesArray == null || candidatesArray.isEmpty()) {
                throw new IOException("No candidates found in the response.");
            }

            // 获取第一个 candidate
            JSONObject firstCandidate = candidatesArray.getJSONObject(0);
            JSONObject content = firstCandidate.getJSONObject("content");

            // 确保 parts 数组存在且包含数据
            JSONArray partsArray = content.getJSONArray("parts");

            if (partsArray == null || partsArray.isEmpty()) {
                throw new IOException("No parts found in the response.");
            }

            // 提取机器人的回复文本
            String botResponse = partsArray.getJSONObject(0).getString("text");

            if (botResponse == null || botResponse.isEmpty()) {
                throw new IOException("No text found in the response.");
            }

            // 返回机器人的回复
            return botResponse;

        } catch (IOException e) {
            // 捕获异常时打印错误日志
            Log.e("GeminiClient", "Error during Gemini API call", e);
            throw e;  // 保留原异常信息
        }

    }
}
